package com.tb.education.common.packets;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.tb.education.common.enumeration.PacketTypeEnum;


import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 消息
 *
 * @author wangze
 * @date 2020-07-08 15:52.
 **/
public class Msg<T extends BaseBody> {

    public static final String SEPARATOR = "@";
    public static final String PREFIX = "[";
    public static final String SUFFIX = "]";

    /**
     * 开始
     */
    private String prefix = PREFIX;


    private Head head;

    private T body;
    /**
     * 结束
     */
    private String suffix = SUFFIX;


    public String getPrefix() {
        return prefix;
    }

    public String getSuffix() {
        return suffix;
    }


    @Override
    public String toString() {
        return prefix + head.toString() + Head.SEPARATOR + body.toString() + suffix;
    }

    public Head getHead() {
        return head;
    }

    public void setHead(Head head) {
        this.head = head;
    }

    public T getBody() {
        return body;
    }

    public void setBody(T body) {
        this.body = body;
    }


    public static <K extends BaseBody> byte[] getByte(Head head, K t) throws UnsupportedEncodingException {
        if (Objects.isNull(head)) {
            return null;
        }
        Msg<K> responseBodyMsg = new Msg<>();
        Head responseHead = new Head();
        BeanUtil.copyProperties(head, responseHead);
        head.setSerialNo(DateUtil.format(DateTime.now(), "yyyyMMddHHmmss") + "1111");
        head.setTime(LocalDateTime.now());
        responseBodyMsg.setHead(responseHead);
        responseBodyMsg.setBody(t);
        head.setPacketLength(responseBodyMsg.getBody().toString().length());
        return responseBodyMsg.toString().getBytes(DevicePacket.CHARSET);
    }

    /**
     * 上报响应
     * @param head
     * @param t
     * @param <K>
     * @return
     * @throws UnsupportedEncodingException
     */
    public static <K extends BaseBody> byte[] getServerToClientByte(Head head, K t) throws UnsupportedEncodingException {
        head.setPacketType(PacketTypeEnum.SERVER_TO_CLIENT_RESPONSE);
        return Msg.getByte(head, t);
    }


}
